<template>
  <div class="radar-chart-radar-wrapper">
    <canvas
      id="radar-chart"
      class="radar-chart"
      width="568"
      height="504"
      style="width: 284px;height: 252px;"
    >
      Your browser does not support the HTML canvas tag.
    </canvas>
  </div>
</template>
<script>
import * as CONSTANTS from '@/constants/index'
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
      required: true,
    },
  },
  components: {},
  data() {
    return {
      canvas: null,
      dashCircleCtx: null, //虚线圈画布
      crossLineCanvas: null,
      crossLineCtx: null, //交叉线画布
      circleCount: 5, //虚线圈数量
      circularSectorCount: 8, //一个圆的扇形数量
      times: 2, //倍数(画布比正常了一倍，所以半径缩放一倍)
      originOutermostCircularRadius: 100, //最外层圆的半径 (这里因为画布缩放的原因，所以双倍了)
      dotRadius: 4, //雷达图坐标上的圆点
      originX: 0, //坐标中心X
      originY: 0, //坐标中心Y
      polygonPoints: [], //交叉线顶点坐标
      radarVertex: [], //雷达图顶点坐标
      fullscore: 100, //满分
    }
  },
  computed: {
    outermostCircularRadius() {
      return this.times * this.originOutermostCircularRadius
    },
    circularSectorAngle() {
      return (Math.PI * 2) / this.circularSectorCount
    },
  },
  mounted() {
    this.onInitCanvas()
    this.convertCanvasToImage()
  },
  filters: {},
  watch: {},
  methods: {
    onInitCanvas() {
      this.canvas = document.getElementById('radar-chart')
      const canvasWidth = this.canvas.width
      const canvasHeight = this.canvas.height

      this.originX = canvasWidth / 2
      this.originY = canvasHeight / 2

      /**
       * dashCircleCtx画布
       * 让canvas的坐标原点位于 canvas的中心位置
       */
      this.dashCircleCtx = this.canvas.getContext('2d')
      this.dashCircleCtx.translate(this.originX * 1, this.originY * 1)
      this.dashCircleCtx.setLineDash([5, 10])
      this.dashCircleCtx.strokeStyle = '#bfbfbf'
      this.dashCircleCtx.setLineWidth = 1

      // this.dashCircleCtx.scale(dpr, dpr)

      this.onDrawCircle()
      this.onDrawCrossLine()
      this.onDrawRadar()
      this.onDrawText()
    },
    //绘制虚线圆
    onDrawCircle() {
      let dashCircleCtx = this.dashCircleCtx
      const circleCount = this.circleCount
      const circularSectorCount = this.circularSectorCount
      let r = this.outermostCircularRadius / circleCount
      let currentRadius = 0

      this.dashCircleCtx.setLineDash([5, 10])

      for (let i = 0; i < circleCount; i++) {
        currentRadius = r * (i + 1)
        for (let j = 0; j < circularSectorCount; j++) {
          dashCircleCtx.beginPath()
          const x = currentRadius * Math.cos(this.circularSectorAngle * j)
          const y = currentRadius * Math.sin(this.circularSectorAngle * j)
          const angle = this.circularSectorAngle * (j + 1)
          // 记录最外层多边形各个顶点的坐标
          if (i === circleCount - 1) {
            let roundX = Math.round(x)
            let roundY = Math.round(y)
            // console.log(`roundX: ${roundX}, roundY: ${roundY}`)

            this.polygonPoints.push([roundX, roundY])
          }

          dashCircleCtx.arc(0, 0, currentRadius, 0, angle, false)
          dashCircleCtx.closePath()
        }

        dashCircleCtx.stroke()
      }
    },
    //绘制交叉线
    onDrawCrossLine() {
      this.dashCircleCtx.save()
      this.dashCircleCtx.beginPath()

      this.dashCircleCtx.setLineDash([])
      this.dashCircleCtx.strokeStyle = '#bfbfbf'
      this.dashCircleCtx.setLineWidth = 1

      for (let i = 0; i < this.polygonPoints.length; i++) {
        this.dashCircleCtx.moveTo(0, 0)
        this.dashCircleCtx.lineTo(
          this.polygonPoints[i][0],
          this.polygonPoints[i][1]
        )
      }

      // this.dashCircleCtx.moveTo(10, 10)
      // this.dashCircleCtx.lineTo(20, 20)

      this.dashCircleCtx.stroke()
      this.dashCircleCtx.restore()
    },
    //绘制雷达图
    onDrawRadar() {
      this.dashCircleCtx.save()
      this.dashCircleCtx.beginPath()

      let xList = []
      let yList = []
      let data = this.list
      let radius = this.outermostCircularRadius
      let angle = this.circularSectorAngle
      let fullscore = 100

      for (let i = 0; i < this.circularSectorCount; i++) {
        let score = data[i].score * 1
        let scorePercent = score / fullscore
        let cosineResult = Math.cos(angle * i) * scorePercent
        let sineResult = Math.sin(angle * i) * scorePercent
        let xRadarVertex = radius * cosineResult * 1
        let yRadarVertex = radius * sineResult * 1

        xList.push(cosineResult)
        yList.push(sineResult)

        this.radarVertex.push([xRadarVertex, yRadarVertex])
      }

      this.dashCircleCtx.beginPath()
      for (let i = 0; i < this.circularSectorCount; i++) {
        i === 0
          ? this.dashCircleCtx.moveTo(
              this.radarVertex[i][0],
              this.radarVertex[i][1]
            )
          : this.dashCircleCtx.lineTo(
              this.radarVertex[i][0],
              this.radarVertex[i][1]
            )
      }
      this.dashCircleCtx.fillStyle = 'rgba(255,102,102,0.32)'
      this.dashCircleCtx.strokeStyle = '#ff6666'
      this.dashCircleCtx.fill()
      this.dashCircleCtx.closePath()
      this.dashCircleCtx.stroke()

      this.dashCircleCtx.setLineDash([])
      this.dashCircleCtx.stroke()
      this.dashCircleCtx.restore()

      this.onDrawRadarVertexDot()
    },
    //绘制雷达图坐标圆点
    onDrawRadarVertexDot() {
      this.dashCircleCtx.save()
      const radarVertex = this.radarVertex
      const dotRadius = this.dotRadius
      const len = radarVertex.length

      const rqDrawDox = (currentDotRadius) => {
        for (let i = 0; i < len; i++) {
          this.dashCircleCtx.beginPath()
          this.dashCircleCtx.fillStyle = '#ff6666'
          this.dashCircleCtx.arc(
            radarVertex[i][0],
            radarVertex[i][1],
            currentDotRadius,
            0,
            2 * Math.PI
          )
          this.dashCircleCtx.fill()
        }
        if (currentDotRadius < dotRadius) {
          requestAnimationFrame(() => {
            rqDrawDox(currentDotRadius + 0.5)
          })
        }
      }
      rqDrawDox(1)

      this.dashCircleCtx.restore()
    },
    //绘制雷达图坐标文字
    onDrawText() {
      const polygonPoints = this.polygonPoints

      for (let i = 0; i < polygonPoints.length; i++) {
        const { name, color, textAlign, indentX, indentY } = this.list[i]

        this.dashCircleCtx.save()
        this.dashCircleCtx.translate(polygonPoints[i][0], polygonPoints[i][1])

        this.dashCircleCtx.textAlign = textAlign
        this.dashCircleCtx.font =
          'normal normal normal 24px SourceHanSansCN-Normal'
        this.dashCircleCtx.fillStyle = color

        this.dashCircleCtx.fillText(name, indentX, indentY)
        this.dashCircleCtx.restore()
      }
    },
    convertCanvasToImage() {
      let canvas = document.getElementById('radar-chart')
      var image = new Image()
      let src = canvas.toDataURL('image/png')
      this.$store.commit(CONSTANTS.COMMIT_UPDATE_CANVASSRC, src)
    },
  },
}
</script>

<style lang="less" scoped>
.radar-chart-radar-wrapper {
  width: 100%;
  // height: 252px;
  // min-height: 100%;
  // background-color: #ff0000;
}

.radar-chart {
  // width: 284px;
  // height: 252px;
  // min-height: 100%;
  // background-color: #f6f7f8;
  margin: 0 auto;
  display: block;
}
</style>
